package com.company.aicrawlers.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.aicrawlers.entity.CollectTaskQuestion;
import com.company.aicrawlers.entity.Question;
import com.company.aicrawlers.mapper.CollectTaskQuestionMapper;
import com.company.aicrawlers.mapper.QuestionMapper;
import com.company.aicrawlers.service.CollectTaskQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 任务-问句关联 Service实现类
 * 
 * @author AI Crawlers
 * @since 2025-10-10
 */
@Slf4j
@Service
public class CollectTaskQuestionServiceImpl extends ServiceImpl<CollectTaskQuestionMapper, CollectTaskQuestion> 
        implements CollectTaskQuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchCreate(Long taskId, List<Long> questionIds, Integer totalPlatformCount) {
        // 查询问句内容
        List<Question> questions = questionMapper.selectBatchIds(questionIds);
        Map<Long, String> questionContentMap = questions.stream()
                .collect(Collectors.toMap(Question::getQuestionId, Question::getQuestionContent));

        List<CollectTaskQuestion> list = new ArrayList<>();
        for (Long questionId : questionIds) {
            CollectTaskQuestion taskQuestion = new CollectTaskQuestion();
            taskQuestion.setTaskId(taskId);
            taskQuestion.setQuestionId(questionId);
            taskQuestion.setQuestionContent(questionContentMap.get(questionId));
            taskQuestion.setExecuteStatus("pending");
            taskQuestion.setCompletedPlatformCount(0);
            taskQuestion.setTotalPlatformCount(totalPlatformCount);
            taskQuestion.setCreateTime(LocalDateTime.now());
            list.add(taskQuestion);
        }
        this.saveBatch(list);
        log.info("批量创建问句关联成功, taskId={}, questionCount={}", taskId, questionIds.size());
    }

    @Override
    public List<CollectTaskQuestion> getByTaskId(Long taskId) {
        LambdaQueryWrapper<CollectTaskQuestion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CollectTaskQuestion::getTaskId, taskId);
        wrapper.orderByAsc(CollectTaskQuestion::getQuestionId);
        return this.list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCompletedPlatformCount(Long taskId, Long questionId) {
        LambdaUpdateWrapper<CollectTaskQuestion> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(CollectTaskQuestion::getTaskId, taskId);
        wrapper.eq(CollectTaskQuestion::getQuestionId, questionId);
        wrapper.setSql("completed_platform_count = completed_platform_count + 1");

        this.update(wrapper);

        // 查询是否全部平台完成
        CollectTaskQuestion taskQuestion = this.getOne(
                new LambdaQueryWrapper<CollectTaskQuestion>()
                        .eq(CollectTaskQuestion::getTaskId, taskId)
                        .eq(CollectTaskQuestion::getQuestionId, questionId)
        );

        if (taskQuestion != null && 
            taskQuestion.getCompletedPlatformCount().equals(taskQuestion.getTotalPlatformCount())) {
            // 全部平台完成，更新状态
            taskQuestion.setExecuteStatus("completed");
            taskQuestion.setCompleteTime(LocalDateTime.now());
            this.updateById(taskQuestion);
            log.info("问句全部平台采集完成, taskId={}, questionId={}", taskId, questionId);
        }

        log.debug("更新问句完成平台数, taskId={}, questionId={}", taskId, questionId);
    }
}

